package com.qianfeng.android.baoman.task;


import android.os.AsyncTask;
import android.os.Environment;
import android.view.View;
import android.widget.ProgressBar;

import com.qianfeng.android.baoman.util.HttpTool;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipInputStream;

/**
 * Created by zhangkx on 2015/3/20.
 */
public class ZipDownloadTask extends AsyncTask<String, Integer, String> {

    private MyInterface myInterface;
    private ProgressBar progressBar;

    public ZipDownloadTask(MyInterface myInterface, ProgressBar progressBar) {
        this.myInterface = myInterface;
        this.progressBar = progressBar;
    }

    @Override
    protected String doInBackground(String... params) {

        String url = params[0];
        String name = params[1];
        InputStream inputStream = null;
        byte[] bytes = null;
//        byte[] bytes = HttpTool.get(param);
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            inputStream = response.getEntity().getContent();
            long file_length = response.getEntity().getContentLength();
            int len = 0;
            byte[] data = new byte[1024];
            int total_length = 0;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            while ((len = inputStream.read(data)) != -1) {
                total_length += len;
                int value = (int) ((total_length / (float) file_length) * 100);
                publishProgress(value);
                outputStream.write(data, 0, len);
            }
            bytes = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }


        if (bytes != null && bytes.length > 0) {
            ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
//            ZipInputStream gin = new ZipInputStream(bin);
            //获取sd卡的路径
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File sdCardPath = Environment.getExternalStorageDirectory();

                File cacheFile = new File(sdCardPath, "baozoumanhua");
                if (!cacheFile.exists()) {
                    cacheFile.mkdirs();
                }
                File targetFile = new File(cacheFile, name);
                boolean bok = true;
                if (!targetFile.exists()) {
                    try {
                        bok = targetFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bok) {
                    OutputStream outputStream = null;

                    try {
                        //写文件
                        outputStream = new FileOutputStream(targetFile);
                        byte[] buffer = new byte[1024 * 1024];
                        int realLength = bin.read(buffer);
                        while (realLength != -1) {
                            outputStream.write(buffer, 0, realLength);
                            realLength = bin.read(buffer);
                        }
//                                        outputStream.write(bytes, 0, bytes.length);
//                                        upZipFile(cacheFile, "baozoumanhua" + name);
//                                    //解压缩
//                                    ZipFile zipFile = new ZipFile(cacheFile);
//                                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
//                                    zipInputStream = new ZipInputStream(byteArrayInputStream);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (outputStream != null) {
                                outputStream.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            } else {
                throw new IllegalArgumentException("cacheFile must set context or device has a sd card");
            }
        }


        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        myInterface.backResult();
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressBar.setVisibility(View.VISIBLE);
    }


}
